package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.handler.PortInfo;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * @author: atguigu
 * @create: 2023-07-25 15:43
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    public String bucketName;

    @Value("${minio.endpointUrl}")
    public String endpointUrl;


    /**
     * 文件上传，将文件上传到minIO返回文件在线地址
     *
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //1.判断存储空间是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                //2.如果不存在新建存储空间 注意：存储空间权限一定设置为Public,手动修改
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            //3.生成全局唯一文件名称 gmall/20230725/xxx.png
            String folderName = DateUtil.formatDate(new Date());
            String extName = FilenameUtils.getExtension(file.getOriginalFilename());
            String fileName = folderName + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + extName;

            //4.将文件上传到MInIO
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            //5.拼接得到文件在线地址 http://192.168.200.128:9000/存储空间名称/目录/文件标识
            return endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            log.error("[文件上传]失败：{}", e);
            throw new RuntimeException(e);
        }
    }
}
